package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-05-27
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    /**
     * 入住申请
     * */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
        //校验老人是否已经入住
        String idCardNo = checkInApplyDto.getCheckInElderDto().getIdCardNo();
        //根据老人身份证号查询老人表，入住状态为1
        Elder elder = elderMapper.selectElderByIdCardNo(idCardNo);
        if(ObjectUtils.isNotEmpty(elder)){
            throw new BaseException("该老人已经入住");
        }
        //更新床位状态为已入住
        Bed bed = bedMapper.selectBedById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //新增或更新老人
        elder = insertOrUpdateElder(bed, checkInApplyDto.getCheckInElderDto());

        //新增签约办理
        Contract contract = BeanUtil.toBean(checkInApplyDto.getCheckInContractDto(), Contract.class);
        contract.setElderId(elder.getId());
        contract.setContractNumber("HT"+CodeGenerator.generateContractNumber());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        contract.setStatus(0);
        contract.setSortOrder(0);
        contractMapper.insert(contract);

        //新增入住信息
        CheckIn checkIn = BeanUtil.toBean(checkInApplyDto.getCheckInConfigDto(), CheckIn.class);
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setRemark(JSONUtil.toJsonStr(checkInApplyDto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkIn.setSortOrder(0);
        checkInMapper.insert(checkIn);

        //新增入住配置
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInApplyDto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfig.setSortOrder(0);
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增或更新老人
     * */
    private Elder insertOrUpdateElder(Bed bed, CheckInElderDto checkInElderDto) {
        //将老人的属性值从请求参数中拷贝到新建的老人对象中
        Elder elder = BeanUtil.toBean(checkInElderDto, Elder.class);
        elder.setStatus(1);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());

        //查询养老院是否存在该老人
        Elder tempElder = elderMapper.selectElderByIdCardNo(elder.getIdCardNo());
        if(ObjectUtils.isNotEmpty(tempElder)){
            //老人存在时，则更新信息
            elderMapper.updateById(elder);
        }else{
            //老人不存在时，则新增
            elderMapper.insert(elder);
        }
        return elder;
    }

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckInDetailVo selectCheckInById(Long id)
    {
        //1、根据入住id获取老人的信息
        //1.1 获取老人id
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        Long elderId = checkIn.getElderId();
        //1.2 根据老人id获取老人的信息
        Elder elder = elderMapper.selectElderById(elderId);
        //1.3 将老人信息封装到CheckInElderVo中
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);

        //2、根据老人的id获取老人的家属信息
        List<ElderFamilyVo> elderFamilyVoList = JSONUtil.toList(JSONUtil.parseArray(checkIn.getRemark()), ElderFamilyVo.class);

        //3、根据老人入住id获取入住配置信息
        LambdaQueryWrapper<CheckInConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CheckInConfig::getCheckInId, id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(queryWrapper);
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);

        //4、根据老人id获取签约办理信息
        LambdaQueryWrapper<Contract> contractQueryWrapper = new LambdaQueryWrapper<>();
        contractQueryWrapper.eq(Contract::getElderId, elderId);
        Contract contract = contractMapper.selectOne(contractQueryWrapper);

        //5、补全数据信息
        checkInConfigVo.setStartDate(contract.getStartDate());
        checkInConfigVo.setEndDate(contract.getEndDate());
        
        return new CheckInDetailVo(checkInElderVo, elderFamilyVoList, checkInConfigVo, contract);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }


}
